
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////Author: Shahab.Alishahian@gmail.com SA	
///////////////Target:The following methods are here to handle jcomment control events.
///////////////Version:1.1
///////////////CopyRight: 2014 Noranj Co.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


//*************************************************************************************************************
// To get all querystring parameters
//*************************************************************************************************************
function getQueryStringParams(sParam) {
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam) {
            return sParameterName[1];
        }
    }
  }


//*************************************************************************************************************
//Log in to facebook account
//*************************************************************************************************************
function loggedin() {
    FB.getLoginStatus(function (response) {
        if (response.status === 'connected') {
            FB.api('/me', function (user) {
                if (!($("#fbid").val()) && ($("#jbUserName").val())) {
                    alert('Authentication Failed!');
                }
                else {
                    $("#jcfbid").val(user.id);
                    $("#jcFirstName").val(user.first_name);
                    $("#jcLastName").val(user.last_name);
                    $("#jcUserName").val(user.email);
                    $("#jcEmailAddress").val(user.email);
                    $('.imageMeRef').attr("src",  'https://graph.facebook.com/' + $('#jcfbid').val() + '/picture');
    		    	$("#jcFbLoginDiv").hide();
    		    	$("#jcOpenComment").show();
                    addUser();
                }
            });
        }
    });
}

//*************************************************************************************************************
//Saving board into Google App Store
//*************************************************************************************************************

function saveBoard(){
	if( $("#jcBoardId").val()!='0')
		return
	var today = new Date();
	
	//Create boardItem object
	var boardItemData = {};
	boardItemData['description'] =  $('meta[name="Description"]').attr('content'); 
	boardItemData['imageURL'] = $("#jcImageUrl").val();
	boardItemData['title'] =  $("meta[property='og\\:title']").attr("content");
	boardItemData['merchantId'] =  $("#jcMerchantId").val();
	boardItemData['url'] = $("#jcPageUrl").val();
	boardItemData['uniqueId'] = 0;

	//Create board object and add the boardItem to it.
    var boardData = {};
	boardData['boardCategory'] = 'comment';
	boardData['boardDescription'] =  $('meta[name="Description"]').attr('content');
	boardData['boardItem'] = boardItemData;
	boardData['boardKeywords'] = '1';
	boardData['boardName'] = '1';
	boardData['boardType'] = 'PUBLIC';
	boardData['boardTitile'] = $('meta[name="Keywords"]').attr('content'); ;
	boardData['dateCreated'] = returnToday();
	//boardData['friendIds'] = null;
	boardData['merchantId'] = $("#jcMerchantId").val();
	boardData['userId'] = $("#jcOwnerId").val();
	
	
	//call add board from gapimehtod.js		
	addBoard(boardData);  
	delete boardData;
	delete contacts0;
	delete contacts1;
}

//*************************************************************************************************************
//Add discussion in board 
//*************************************************************************************************************
function addComment(){
	//Create boardItemDiscussion object.
	var actionRequired = false;
	if ($("#jcAskOfAgent").is(':checked'))
		actionRequired = true;
	var boardItemDiscussionData = {};
	boardItemDiscussionData['boardItemId'] =$("#jcBoardId").val();
	boardItemDiscussionData['actionRequired'] = actionRequired;
	boardItemDiscussionData['discussion'] = $("#textAreaComment").val();
	boardItemDiscussionData['faceBookReference'] = '0';
	boardItemDiscussionData['userId'] = $("#jcUserId").val();
	addBoardItemDiscussion(boardItemDiscussionData);
}

//*************************************************************************************************************
// Add logged in user into J dataStore
//*************************************************************************************************************

function addUser(){
	FB.api('/me', function (user) {
        if (!($("#jcfbid").val()) && ($("#jcUserName").val())) {
            alert('Authentication Failed!');
        }
        else {
        	var tempdata = {};
   		 	tempdata['address'] = '0';
			tempdata['age'] = '0';
			tempdata['city'] = '0';
			tempdata['country'] = '0';
			tempdata['dateCreated'] = returnToday();
			tempdata['email'] = user.email;
			tempdata['facebookId'] = user.id;
			tempdata['firstName'] = user.first_name;
			tempdata['gender'] = '0';
			tempdata['lastName'] = user.last_name;
			tempdata['merchantId'] = $("#jcMerchantId").val();
			setAddUser(tempdata,null); //this method source file is server.js
        }
	});
}
//*************************************************************************************************************
//Retrun the current date on client side
//*************************************************************************************************************
function returnToday(){
	  var today = new Date();
      var dd = today.getDate();
      var mm = today.getMonth()+1;
      var yyyy = today.getFullYear();
      
      if(dd<10){dd='0'+dd;} 
      if(mm<10){mm='0'+mm;}
      
      var returnToday = yyyy + '' + mm +'' + dd ;
      delete yyyy;
      delete mm;
      delete dd;
      return returnToday;
}
//*************************************************************************************************************
// Create the html of list comments. 
//*************************************************************************************************************

function createConversation(data,contributer){
	var strReturn ='';
		strReturn += '<div class="uiCommentRow"><table border="0" cellpadding="0" cellspacing="0" width="100%">';
			strReturn += '<tr>';
				strReturn += '<td rowspan="3" valign="top" style="width:60px">';
				strReturn += '<a href="https://www.facebook.com/' + contributer.facebookId + '" target="_blank" >';
				strReturn += '<img src= "https://graph.facebook.com/' + contributer.facebookId + '/picture" ></a></td>';
				strReturn += '<td colspan="3" valign="top">';
					strReturn += '<div id="'+ data.id + '" >';
					strReturn += '<Span class="textUser" >' + contributer.firstName + ' ' + contributer.lastName + '</Span>';
					strReturn += '</div>' ;
				strReturn += '</td>';
				strReturn += '<td width="20px"><a href="" id="removeDiscussion" class="fancyboxclose" onclick="removeDisscussionMine(\''+ data.id + '\')"></a></td>';
			strReturn += '</tr>';
			strReturn += '<tr>';
				strReturn += '<td colspan="3">'+ data.discussion+'</td>';
				strReturn += '<td ></td>';
			strReturn += '</tr>';
			strReturn += '<tr>';
				strReturn += '<td><div style="width:60px;white-space: nowrap;"><a class="textLink" id="rpl'+ data.id + '">Reply</a></div></td>';
				strReturn += '<td></td>';
				strReturn += '<td></td>';
				strReturn += '<td></td>';
			strReturn += '</tr>';
		strReturn += '</table></div>';
	
	//console.log(strReturn);
	return strReturn;
}

function addAConversation(){
	var strReturn ='';
		strReturn += '<div class="uiCommentRow"><table border="0" cellpadding="0" cellspacing="0" width="100%">';
			strReturn += '<tr>';
				strReturn += '<td rowspan="3" valign="top" style="width:60px"><img src= "https://graph.facebook.com/' + $("#jcfbid").val() + '/picture" ></td>';
				strReturn += '<td colspan="3" valign="top">';
					strReturn += '<div id="'+ $("#jcUserId").val() + '" >';
					strReturn += '<Span class="textUser" >' + $("#jcFirstName").val() + ' ' + $("#jcLastName").val() + '</Span>';
					strReturn += '</div>' ;
				strReturn += '</td>';
			strReturn += '</tr>';
			strReturn += '<tr>';
				strReturn += '<td colspan="3">'+ $("#textAreaComment").val()+'</td>';
			strReturn += '</tr>';
			strReturn += '<tr>';
				strReturn += '<td><div style="width:60px;white-space: nowrap;"><a class="textLink" id="rpl'+ $("#jcUserId").val() + '">Reply</a></div></td>';
				strReturn += '<td></td>';
				strReturn += '<td></td>';
			strReturn += '</tr>';
		strReturn += '</table></div>';
	
		$("#boardCommentList").prepend(strReturn);
		$("#boardCommentList").show();
}


//*************************************************************************************************************
//Load board by URL string. 
//*************************************************************************************************************


function loadBoard(url){
	 getBoardbyUrl(encodeURIComponent(url));
}

//*************************************************************************************************************
//retrieving client info 
//*************************************************************************************************************

function getSYSClientInfo (){
	var date = new Date();
	date.setTime(date.getTime() + (60 * 1000))
	
		$("#jcCountry").val('CA');
		$("#jcCity").val('N\A');
		$("#jcIPAddress").val('0.0.0.0');
	
//	var jqxhr =	$.get("http://ipinfo.io", 
//		function (response) {
//			var tempData= {};
//			tempData['ip'] = response.ip;
//			tempData['city'] = response.city ;
//			tempData['country'] = response.country ;
//			tempData['more'] = JSON.stringify(response, null, 4);
//		}, "jsonp");
//
//	jqxhr.always(function() {
//		var clientInfo = {} ; 
//		clientInfo = JSON.parse(JSON.stringify(jqxhr));
//		$("#jcCountry").val(clientInfo.responseJSON.country);
//		$("#jcCity").val(clientInfo.responseJSON.city);
//		$("#jcIPAddress").val(clientInfo.responseJSON.ip);
//	});
	
}
		
		
		
		
		